package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.script.pojo.vo.ScriptVO;
import com.xbongbong.pro.smartsettings.pojo.dto.AiAssistantFixDataDTO;
import com.xbongbong.saas.service.RepairDataService;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/***
 * 智能助手修改脚本
 *
 * @author hongxiao
 * @date 2022-03-10 14:06
 * @since
 * @version
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX+"/script/aiAssistant")
public class AiAssistantScriptController {

    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private RepairDataService repairDataService;


    @RequestMapping(value = "/fixMenuId", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixMenuId(@RequestBody @Valid AiAssistantFixDataDTO aiAssistantFixDataDTO, BindingResult br) throws XbbException {
        if (!proBaseConfig.getXbbCode().equals(aiAssistantFixDataDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        XbbResponse<ScriptVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ScriptVO scriptVO = repairDataService.fixMenuId(aiAssistantFixDataDTO);
                response = new XbbResponse<>(scriptVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }


}
